package com.authine.cloudpivot.ext.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.authine.cloudpivot.engine.api.facade.WorkflowInstanceFacade;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.*;
import com.authine.cloudpivot.engine.api.utils.FileHelper;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import jodd.datetime.TimeUtil;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.*;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 课程评审
 */
@Slf4j
@RestController
@RequestMapping("/api/Coursereview")
public class CourseReviewController extends BaseController {

    @PersistenceContext
    EntityManager entityManager;
//
//    /**
//     * 评分
//     * @param map
//     * @return
//     */
//    @PostMapping("/score")
//    public ResponseResult score(@RequestBody Map<String,String> map){
//        log.info("获取参数：map{}",map);
//        if (map.isEmpty()){
//            return getErrResponseResult(500L,"参数为空");
//        }
//        String objId = map.get("objId");
//        String kcpfid = map.get("kcpfid");
//        //获取课程申报里面配置的评分标准
//        String pfbzId = getBizObjectFacade().getBizObject("kcsb", objId).getString("pfbz");
//        String kcmc = getBizObjectFacade().getBizObject("kcsb", objId).getString("courseName");
//        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("pzpfbzNew", pfbzId);
//        Map<String, Object> data = bizObject.getData();
//        Object lx = data.get("lx");
//        List<Map<String, Object>> pfbzbNew = (List<Map<String, Object>>) data.get("pfbzbNew");
//        List<Map<String,Object>> list = new ArrayList<>();
//        for (Map<String,Object> m: pfbzbNew) {
//            HashMap<String, Object> hashMap = new HashMap<>();
//            hashMap.put("wd",m.get("wd"));
//            hashMap.put("xd",m.get("xd"));
//            hashMap.put("zgfz",m.get("zgfz"));
//            hashMap.put("dj",m.get("dj"));
//            hashMap.put("rowStatus","Added");
//            list.add(hashMap);
//        }
//        //生成评分表
//        BizObjectCreatedModel bizObj = new BizObjectCreatedModel();
//        bizObj.setSchemaCode("pfbNew");
//        bizObj.put("kcid",objId);
//        bizObj.put("courseName",kcmc);
//        bizObj.put("glpfb",pfbzId);
//        bizObj.put("pflx",lx);
//        bizObj.put("dfbNew",list);
//        String s = getBizObjectFacade().saveBizObject(getUserId(), bizObj, false);
//        StringBuilder sql=new StringBuilder("update  `iwrwy_kcpf` set pfbid='")
//                .append(s).append("' where id ='").append(kcpfid).append("'");
//        int i = entityManager.createQuery(sql.toString()).executeUpdate();
//        return getOkResponseResult(s,"创建评分表成功");
//    }

    /**
     * 提交评分
     *
     * @param maps
     * @return
     */
    @PostMapping("/submitResults")
    public ResponseResult submitResults(@RequestBody List<Map<String, Object>> maps) {
        log.info("获取参数:map{}", maps);
        if (maps.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        //判断是否有空评分项
        boolean sfwc=false;
        StringBuilder  title=new StringBuilder();
        for (Map m: maps) {
            //评委评分表的id
            String objId = (String) m.get("objId");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcpf", objId);
            //未填完不能提交
            String lx = bizObject.getString("lx");
            List<Map<String, Object>> kcpfzb =(List<Map<String, Object>>) bizObject.get("kcpfzb");
            if ("分值".equals(lx)){
                sfwc=kcpfzb.stream().allMatch(s-> s.get("df")!=null&&s.get("df")!="");
            }
            if ("等级".equals(lx)){
                sfwc=kcpfzb.stream().allMatch(s-> s.get("dj")!=null&&s.get("dj")!="");
            }
            if (!sfwc){
                title.append("活动："+bizObject.getString("hdmc")+",课程名称："+bizObject.getString("courseName")+"未完成评分;");
            }
        }
        if(StringUtil.isNotEmpty(title)){
            return  getErrResponseResult(500L,title.toString());
        }else {
            for (Map map : maps) {
                //评委评分表的id
                String objId = (String) map.get("objId");
                BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcpf", objId);
                String dqyw = bizObject.getString("dqyw");
                if ("已提交".equals(bizObject.getString("zt"))) {
                    return getErrResponseResult(500L, "请勿重复提交");
                }
                Map<String, Object> data = bizObject.getData();
                Map<String, Object> glsbd = (Map<String, Object>) data.get("glsbd");
                String sbdid = (String) glsbd.get("id");
                //分值类型回写申报活动
                BizObjectCreatedModel bizObject1 = getBizObjectFacade().getBizObject("kcsbNew", sbdid);
                BizObjectCreatedModel sbdObj = new BizObjectCreatedModel("kcsbNew", bizObject1.getData(), false);
                Map<String, Object> map1 = new HashMap<>();
                List<Map<String, Object>> list = new ArrayList<>();
                if ("分值".equals(bizObject.getString("lx"))) {
                    Object sumdf = bizObject.get("sumdf");
                    SelectionValue selectionValue = new SelectionValue();
                    selectionValue.setId(getUserId());
                    selectionValue.setType(UnitType.USER);
                    map1.put("pw", Collections.singletonList(selectionValue));
                    map1.put("zf", sumdf);
                    map1.put("rowStatus", "Added");
                    list.add(map1);
                } else {
                    SelectionValue selectionValue = new SelectionValue();
                    selectionValue.setId(getUserId());
                    selectionValue.setType(UnitType.USER);
                    map1.put("pw", Collections.singletonList(selectionValue));
                    map1.put("rowStatus", "Added");
                    list.add(map1);
                }
                if ("jcpstj".equals(dqyw)) {
                    sbdObj.put("psdfb", list);
                }

                if ("lrcpgl".equals(dqyw)) {
                    sbdObj.put("cppfb", list);
                }

                if ("zpgl".equals(dqyw)) {
                    sbdObj.put("zppfb", list);
                }
                //保存评委评分
                String s1 = getBizObjectFacade().saveBizObject(bizObject1.getCreater().getId(), sbdObj, false);

                BizObjectCreatedModel bizObj = new BizObjectCreatedModel("kcpf", new HashMap<>(), false);
                bizObj.setId(objId);
                bizObj.put("zt", "已提交");

                //修改评审进度
                //获取评委和评分标准
                StringBuilder sql = new StringBuilder("select psz,pfbz from iwrwy_pwfz where INSTR(kcid,'");
                sql.append(sbdid).append("') and dqyw='").append(dqyw).append("' order by createdTime desc");
                List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                String pszid = (String) sqllist.get(0).get("psz");
                BizObjectCreatedModel pwObject = getBizObjectFacade().getBizObject("pzpszNew", pszid);
                List<SelectionValue> ry = (List<SelectionValue>) pwObject.get("ry");
                //评委总数
                int size = ry.size();
                //threadPool.schedule(() -> {
                String s = getBizObjectFacade().saveBizObject(getUserId(), bizObj, false);
                log.info("修改状态成功.s={}", s);
                StringBuilder countSql = new StringBuilder("SELECT count(*) FROM `iwrwy_kcpf`  where glsbd='")
                        .append(sbdid).append("'  and zt='已提交'  and dqyw='").append(dqyw).append("'");
                Query query = entityManager.createNativeQuery(countSql.toString());
                BigInteger count = (BigInteger) query.getSingleResult();
                StringBuilder fs = new StringBuilder().append(count).append("/").append(size);
                BizObjectCreatedModel sbobj = new BizObjectCreatedModel();
                sbobj.setSchemaCode("kcsbNew");
                sbobj.setId(sbdid);
                if ("jcpstj".equals(dqyw)) {
                    sbobj.put("psjd", fs);
                }

                if ("lrcpgl".equals(dqyw)) {
                    sbobj.put("cpjd", fs);
                }

                if ("zpgl".equals(dqyw)) {
                    sbobj.put("zpjd", fs);
                }
                getBizObjectFacade().saveBizObject(sbobj.getCreater().getId(), sbobj, false);
                // }, 3, TimeUnit.SECONDS);
            }
        }



        return getOkResponseResult("提交成功");
    }


//    /**
//     * 修改评分
//     */
//    @PostMapping("/updateScore")
//    public ResponseResult updateScore(@RequestBody Map<String,Object> map){
//        log.info("获取参数:map{}",map);
//        if (map.isEmpty()){
//            return getErrResponseResult(500L,"参数为空");
//        }
//        String objId =(String) map.get("objId");
//        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcpf", objId);
//        //课程id
//        String kcid =(String) bizObject.get("glsbd");
//        //评分表id
//        String pfbid = bizObject.getString("pfbid");
//        String userId = getUserId();
//        StringBuilder sql=new StringBuilder("select id from iwrwy_pfbNew where kcid='").append(kcid).append("' and glpfbz='")
//                            .append(pfbid).append("' and creater='").append(userId).append("'");
//        List resultList = entityManager.createNativeQuery(sql.toString()).getResultList();
//        return getOkResponseResult("修改成功");
//    }

    /**
     * 部门领导审批流程的审批意见存储至公司通知
     * 2022-04-14 初始逻辑：
     * 部门领导审批流程 deptManagerApproveFlow 结束后调用。
     * 获取部门领导审批表单 DepartmentLeaderApproval 中的审批结果（Dropdown_spjg），获取流程的发起人
     * 存数据到公司通知表单（ZCGL_TZTG_SUB）
     * 标题：  【课程评审】基层推荐评审审批_审批通过
     * 内容：  审批意见
     */
    @GetMapping("/sendMessageToZCGL")
    public void sendMessageToZCGL(@RequestParam String id,@RequestParam String workflowInstanceId) {
        //schemaCode写死。便于后续依模型编码排查问题
        BizObjectCreatedModel bmldsp = getBizObjectFacade().getBizObject("DepartmentLeaderApproval", id);

        //h_biz_comment 审批意见表获取审批意见
        WorkflowInstanceFacade workflowInstanceFacade = getWorkflowInstanceFacade();
        WorkflowInstanceModel workflowInstanceModel = workflowInstanceFacade.getByObjectId(id);
        List<BizCommentModel> comments = getBizObjectFacade().getComments(workflowInstanceId, org.apache.commons.lang3.StringUtils.EMPTY);

        //公司通知
        BizObjectCreatedModel gstz = new BizObjectCreatedModel();
        gstz.setSchemaCode("ZCGL_TZTG_SUB");
        gstz.setSequenceStatus("COMPLETED");
        //部门领导审批表单的审批结果数据项
        String spjg = (String) bmldsp.get("Dropdown_spjg");
        String bt = "【课程评审】基层推荐评审审批_";
        String tzbt = org.apache.commons.lang3.StringUtils.isNotBlank(spjg) ? bt + spjg : bt + "无审批结果";
        gstz.put("tzbt", tzbt);
        gstz.put("tzrt", comments.get(comments.size()-1).getContent());
        gstz.put("isRead", "否");
        String gstzObjectId = getBizObjectFacade().saveBizObject(workflowInstanceModel.getOriginator(), gstz, false);
        log.info("存储成功的公司通知表单ID:{}", gstzObjectId);

    }

    /**
     * 启动评审
     * 2022-04-13 增加逻辑：
     * 在启动评审时成功后，获取评审组的用户，向公司通知模型（ZCGL_TZTG_SUB）存储表单数据。每位评审用户一条。
     */
    @PostMapping("/startReview")
    public ResponseResult startReview(@RequestBody List<Map<String, Object>> list, @RequestParam("dqyw") String dqyw) {
        log.info("获取参数，list{}", list);
        if (CollectionUtils.isEmpty(list)) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map<String, Object> map : list) {
            String objId = (String) map.get("objId");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcsbNew", objId);

            //申报课程id
            String id = bizObject.getId();

            //判断是否重复启动
            StringBuilder selectsql = new StringBuilder("select * from iwrwy_kcpf where glsbd='").append(id).append("' and dqyw='").append(dqyw).append("'");
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectsql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isNotEmpty(resultList)) {
//                String dqyw = (String) resultList.get(0).get("dqyw");
//                if (DQYW.equals(dqyw)) {
                return getErrResponseResult(500L, "已启动评审，请勿重复提交");
//                }
            }
            //获取评委和评分标准
            StringBuilder sql = new StringBuilder("select psz,pfbz from iwrwy_pwfz where INSTR(kcid,'");
            sql.append(id).append("') and dqyw='").append(dqyw).append("' order by createdTime desc");
            List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isEmpty(sqllist)) {
                return getErrResponseResult(500L, "课程:" + bizObject.getString("courseName") + "未分配评审组");
            }
            //配置评分标准id
            String pfbzid = (String) sqllist.get(0).get("pfbz");
            BizObjectCreatedModel pfbzObject = getBizObjectFacade().getBizObject("pzpfbzNew", pfbzid);
            List<Map<String, Object>> pfbzbNew = (List<Map<String, Object>>) pfbzObject.get("pfbzbNew");
            List<Map<String, Object>> resultlist = new ArrayList<>();
            for (Map<String, Object> m : pfbzbNew) {
                Map<String, Object> result = new HashMap<>();
                result.put("wd", m.get("wd"));
                result.put("xd", m.get("xd"));
                result.put("zgfz", m.get("zgfz"));
                result.put("ycdj", m.get("dj"));
                result.put("rowStatus", "Added");
                resultlist.add(result);
            }

            //配置评审组id
            String pszid = (String) sqllist.get(0).get("psz");
            BizObjectCreatedModel pszObject = getBizObjectFacade().getBizObject("pzpszNew", pszid);
            List<SelectionValue> ry = (List<SelectionValue>) pszObject.get("ry");
            //获取活动名称
            Map<String, Object> smap = (Map<String, Object>) bizObject.get("RelevanceFormSBHD");
            String hdmc = (String) smap.get("hdmc");
            for (SelectionValue sv : ry) {
                BizObjectCreatedModel bz = new BizObjectCreatedModel();
                bz.setSchemaCode("kcpf");
                bz.setSequenceStatus("DRAFT");
                bz.put("glsbd", objId);
                bz.put("lx", pfbzObject.getString("xzpfblx"));
                bz.put("kcpfzb", resultlist);
                bz.put("zt", "未提交");
                bz.put("kczkfr", bizObject.get("kczkfr"));
                bz.put("courseName", bizObject.get("courseName"));
                bz.put("glhd", bizObject.get("RelevanceFormSBHD"));
                bz.put("hdmc", hdmc);
                bz.put("dqyw", dqyw);
                String s = getBizObjectFacade().saveBizObject(sv.getId(), bz, false);
                System.out.println(s);
            }
            int size = ry.size();
            StringBuilder fs = new StringBuilder().append("0/").append(size);
            BizObjectCreatedModel sbobj = new BizObjectCreatedModel();
            sbobj.setSchemaCode("kcsbNew");
            sbobj.setId(objId);
            if ("jcpstj".equals(dqyw)) {
                sbobj.put("psjd", fs);
            }

            if ("lrcpgl".equals(dqyw)) {
                sbobj.put("cpjd", fs);
            }

            if ("zpgl".equals(dqyw)) {
                sbobj.put("zpjd", fs);
            }
            getBizObjectFacade().saveBizObject(sbobj.getCreater().getId(), sbobj, false);

            //2022-04-13 增加逻辑：
            //在启动评审时成功后，获取评审组的用户，向公司通知模型（ZCGL_TZTG_SUB）存储表单数据。每位评审用户一条。
            //评审组关联单选数据项:psz
            for (SelectionValue selectionValue : ry) {
                //公司通知
                BizObjectCreatedModel gstz = new BizObjectCreatedModel();
                gstz.setSchemaCode("ZCGL_TZTG_SUB");
                gstz.setSequenceStatus("COMPLETED");
                String courseName = (String) bizObject.get("courseName");
                String tzbt = org.apache.commons.lang3.StringUtils.isNotBlank(hdmc) ? "【课程评审】-" + hdmc : "【课程评审】-" + courseName;
                gstz.put("tzbt", tzbt);
                gstz.put("tzrt", "此活动的课程需要你评审");
                gstz.put("isRead", "否");
                String gstzObjectId = getBizObjectFacade().saveBizObject(selectionValue.getId(), gstz, false);
                log.info("存储成功的公司通知表单ID:{}", gstzObjectId);
            }


        }
        return getOkResponseResult("启动评审成功");
    }

    /**
     * 查看评审配置--可能未启用
     */
    @GetMapping("/reviewConfig")
    public ResponseResult reviewConfig(@RequestParam("objId") String objId) {
        log.info("获取参数：objId{}", objId);
        if (StringUtils.isEmpty(objId)) {
            return getErrResponseResult(500L, "参数为空");
        }
        StringBuilder sql = new StringBuilder("select id from iwrwy_pwfz where INSTR(kcid,'");
        sql.append(objId).append("')");
        List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(sqllist)) {
            return getErrResponseResult(500L, "未分配评审配置");
        }
        String id = (String) sqllist.get(0).get("id");
        return getOkResponseResult(id);
    }

    /**
     * 推荐课程--可能未启用
     */
    @PostMapping("/recommend")
    public ResponseResult recommend(@RequestBody List<Map<String, Object>> map) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map<String, Object> m : map) {
            String objId = (String) m.get("objId");
            BizObjectCreatedModel bz = new BizObjectCreatedModel();
            bz.setSchemaCode("kcsbNew");
            bz.setId(objId);
            bz.put("tjzt", "已提交");
            getBizObjectFacade().saveBizObject(bz.getCreater().getId(), bz, false);
        }
        return getOkResponseResult("推荐成功");
    }

    @PostMapping("/upload_file")
    public ResponseResult importScore(MultipartFile file, String code) throws Exception {
        if (StringUtils.isEmpty(code)) {
            return getErrResponseResult(500L, "编码为空");
        }
        String fileName = file.getName();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);

        if (fileName.contains(".") && !org.apache.commons.lang3.StringUtils.equalsAny(fileExtension, new CharSequence[]{"xls", "xlsx"})) {
            log.info("文件格式错误,只支持xlsx或xls格式文件");
            return getErrResponseResult(-1l, "文件格式错误,只支持xlsx或xls格式文件");
        }

        Workbook wb = WorkbookFactory.create(file.getInputStream());

        Sheet sheet = wb.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        List<String> colCode = new ArrayList<>();
        if ("sjgl".equals(code)) {
            // id  课程名   试讲得分 课程等级
            colCode = new ArrayList<>(Arrays.asList("id", "courseName", "sjdf", "kcdj"));
        }
        if ("jgqryfb".equals(code)) {
            // id 课程名  最终得分   最终结果(课程等级)
            colCode = new ArrayList<>(Arrays.asList("id", "courseName", "zzdf", "kcdj", "bmkffw"));
        }
        if ("lrcpgl".equals(code)) {
            //id  课程名   初评得分  初评结果
            colCode = new ArrayList<>(Arrays.asList("id", "courseName", "cpdf", "cpjg"));
        }
        if ("zpgl".equals(code)) {
            //id  课程名   最终得分  课程等级
            colCode = new ArrayList<>(Arrays.asList("id", "courseName", "zzdf", "kcdj"));
        }
        List<String> colName = new ArrayList<>();
        for (int i = 0; i < colCode.size(); i++) {
            colName.add(FileHelper.getStringCellValue(firstRow.getCell(i)));
        }


        int lastRowNum = sheet.getLastRowNum();

        //取出导入数据
        List<Map<String, Object>> scoreList = new ArrayList<>();

        for (int i = 1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            Map<String, Object> scoreMap = new HashMap<>();
            for (int j = 0; j < colCode.size(); j++) {
                Cell cell = row.getCell(j);
                String value = FileHelper.getStringCellValue(cell);
                if (org.apache.commons.lang3.StringUtils.isEmpty(value)) {
                    log.info("{}行{}列不能为空", i + 1, colName.get(j));
                    return getErrResponseResult(-1l, StrUtil.format("{}行{}列不能为空", i + 1, colName.get(j)));
                }

                scoreMap.put(colCode.get(j), value);
            }
            scoreMap.remove("courseName");
            scoreList.add(scoreMap);
        }

        String schemaCode = "kcsbNew";

        //判断课程存在
        List<String> collect = scoreList.stream().filter(m -> {
            boolean exists = getBizObjectFacade().existsBizObject(schemaCode, MapUtils.getString(m, "id", ""));
            return !exists;

        }).map(m -> MapUtils.getString(m, "id", "")).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(collect)) {
            return getErrResponseResult(-1l, StrUtil.format("导入失败:课程id:{} ,不存在课程数据", org.apache.commons.lang3.StringUtils.join(collect, ",")));
        }

        //修改课程表
        List<BizObjectModel> kcsbList = scoreList.stream()
                .map(m -> new BizObjectCreatedModel("kcsbNew", m, false)).collect(Collectors.toList());

        getBizObjectFacade().batchSaveBizObjectModel(getUserId(), kcsbList, DefaultPropertyType.ID.getCode());

        return getOkResponseResult("成功");
    }

    /**
     * 评审组回写课程申报
     */
    @GetMapping("/writeBackkcsb")
    public ResponseResult writeBackkcsb(@RequestParam String objId, @RequestParam String dqyw) {
        log.info("获取参数：objid{},", objId);
        if (StringUtils.isEmpty(objId)) {
            return getErrResponseResult(500L, "参数为空");
        }
        //获取评委和评分标准
        StringBuilder sql = new StringBuilder("select kcid,psz,pfbz from iwrwy_pwfz where id='");
        sql.append(objId).append("' and dqyw='").append(dqyw).append("' order by createdTime desc");
        List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(sqllist)) {
            return getErrResponseResult(500L, "查询结果为空");
        }
        Map<String, Object> objectMap = sqllist.get(0);
        String kcid = (String) objectMap.get("kcid");
        Object psz = objectMap.get("psz");
        Object pfbz = objectMap.get("pfbz");
        String[] split = kcid.split(";");
        for (String s : split) {
//            StringBuilder selectSql = new StringBuilder();
//            selectSql.append("select ShortTextDQYW from iwrwy_kcsbNew where id='").append(s).append("'");
//            List<Map<String, Object>> selectlist = entityManager.createNativeQuery(selectSql.toString()).unwrap(NativeQueryImpl.class)
//                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//            //当前业务
//            String dqyw1 = (String) selectlist.get(0).get("ShortTextDQYW");
            BizObjectCreatedModel bz = new BizObjectCreatedModel();
            bz.setSchemaCode("kcsbNew");
            bz.setId(s);
            if ("jcpstj".equals(dqyw)) {
                bz.put("psz", psz);
                bz.put("pfb", pfbz);
            }
            if ("lrcpgl".equals(dqyw)) {
                bz.put("cppsz", psz);
                bz.put("cppfbz", pfbz);
            }
            if ("zpgl".equals(dqyw)) {
                bz.put("zppsz", psz);
                bz.put("zppfbz", pfbz);
            }
            String id = bz.getCreater().getId();
            getBizObjectFacade().saveBizObject(id, bz, false);
        }
        return getOkResponseResult("成功");
    }

    /**
     * 判断是否已启动评审
     */
    @PostMapping("/judgestarted")
    public ResponseResult judgeStarted(@RequestBody List<Map<String, Object>> map, @RequestParam("dqyw") String dqyw) {
        if (map.isEmpty()) {
            return getErrResponseResult(500L, "参数为空");
        }
        for (Map m : map) {
            String objId = (String) m.get("objId");
            BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("kcsbNew", objId);
            //申报课程id
            String id = bizObject.getId();
            //String shortTextDQYW = bizObject.getString("ShortTextDQYW");

            //判断是否重复启动
            StringBuilder selectsql = new StringBuilder("select * from iwrwy_kcpf where glsbd='").append(id).append("' and dqyw='").append(dqyw).append("'");
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectsql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (CollectionUtils.isNotEmpty(resultList)) {
                return getErrResponseResult(500L, "已启动评审，不可分配评审组");
            }
        }
        return getOkResponseResult("可分配评审组");
    }

    /**
     * 获取附件
     */
    @GetMapping("/getenclosure")
    public ResponseResult getEnclosure(@RequestParam String objId, @RequestParam String code) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(code, objId);
        Object attachment = bizObject.get("attachment");
        return getOkResponseResult(attachment, "返回附件成功");
    }

    /**
     * 判断评分维度是否重复
     */
    @GetMapping("/duplicateDimension")
    public ResponseResult duplicateDimension(@RequestParam String fl, @RequestParam String wd) {
        log.info("获取参数：fl{},wd{}", fl, wd);
        if (StringUtils.isEmpty(fl) || StringUtils.isEmpty(wd)) {
            return getErrResponseResult(500L, "参数为空");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select * from iwrwy_pfwdNew where fl='").append(fl).append("' and wd='").append(wd).append("'");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(resultList)) {
            return getOkResponseResult("可以分配");
        } else {
            return getErrResponseResult(500L, "该分类下维度名称重复");
        }
    }

    /**
     * 获取项点
     */
    @GetMapping("/getItemByDimension")
    public ResponseResult getItemByDimension(@RequestParam String type,@RequestParam String dimension){
        if (StringUtil.isEmpty(type)||StringUtil.isEmpty(dimension)){
            return getErrResponseResult(-1L,"参数为空");
        }
        String[] split = dimension.split(";");
        StringBuilder items=new StringBuilder();
        for (int i = 0; i <split.length; i++) {
            items.append("'").append(split[i]).append("'");
            if (i<split.length-1){
                items.append(",");
            }
        }
        String tableName = getBizObjectFacade().getTableName("pfxdNew");
        StringBuilder sql=new StringBuilder();
        StringBuilder select = new StringBuilder();
        if ("分值".equals(type)){
            select.append("select id,fl,ycwd,xd,zgfz from ");
        }else{
            select.append("select id,fl,ycwd,xd,dj from ");
        }
        sql.append(select).append(tableName)
                .append(" where lx='").append(type).append("' and ycwd in(").append(items).append(") order by ycwd");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(resultList)){
            return getErrResponseResult(-1L,"获取数据为空");
        }
        int i=1;
        for (Map m: resultList) {
            m.put("xh",i++);
        }
        return getOkResponseResult(resultList,"success");
    }
}
